package cn.dhnep.demo.controller;


import cn.dhnep.demo.pojo.Admin;
import cn.dhnep.demo.pojo.AdminRole;
import cn.dhnep.demo.pojo.LoginRecord;
import cn.dhnep.demo.pojo.vo.RespBean;
import cn.dhnep.demo.pojo.vo.RespPageBean;
import cn.dhnep.demo.service.AdminRoleService;
import cn.dhnep.demo.service.AdminService;
import cn.dhnep.demo.util.Constant;
import cn.dhnep.demo.util.Page;
import cn.dhnep.demo.util.ResultMap;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 登录注册模块
 * </p>
 *
 * @author dhn
 * @since 2021-08-09
 */
@RestController
@RequestMapping("/dhn")
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private AdminRoleService adminRoleService;

    private Map<String, Object> result = new HashMap<>();


    @ApiOperation("分页获取所有管理员以及所拥有的角色")
    @GetMapping("getAllAdmin")
    public RespPageBean getAdmin(@RequestParam(defaultValue = "1") Integer currentPage,
                                 @RequestParam(defaultValue = "15") Integer size,
                                 @RequestParam(value = "adminName", required = false) String adminName,
                                 @RequestParam(value = "adminPhone", required = false) String adminPhone,
                                 @RequestParam(value = "adminNickname", required = false) String adminNickname) {
        return adminService.getAllAdmin(currentPage, size, adminName, adminPhone, adminNickname);
    }

    @ApiOperation("登录记录分页查询")
    @RequestMapping("loginrecord")
    public ResultMap<List<LoginRecord>> loginrecordsList(Page page, @RequestParam("limit") Integer limit) throws UnsupportedEncodingException {
        page.setRows(limit);
        List<LoginRecord> loginrecordsList = adminService.selectPageloginrecordList(page);
        int totals = adminService.selectPageloginrecordCount(page);
        page.setTotalRecord(totals);
        return new ResultMap<List<LoginRecord>>("", loginrecordsList, 0, totals);
    }

    @ApiOperation("添加管理员")
    @PostMapping("addAdmin")
    public RespBean addAdmin(@Validated @RequestBody Admin admin) {
        Integer[] roleIds = admin.getRoleIds();
        if (roleIds == null || roleIds.length == 0) return RespBean.error("请至少选择一个角色！");

        if (adminService.count(new QueryWrapper<Admin>().eq("admin_nickName", admin.getAdminNickname())) > 0) {
            return RespBean.error("该用户名已存在！");
        }

        admin.setCreateTime(new Date()).setAdminState(1);
        if (adminService.addAdminRole(admin)) {
            return RespBean.success("添加管理员成功！");
        }
        return RespBean.error("添加管理员失败！");
    }

    @ApiOperation("更新管理员信息")
    @PutMapping("updateAdmin")
    public RespBean updateAdmin(@Validated @RequestBody Admin admin) {
        Integer[] roleIds = admin.getRoleIds();
        if (roleIds == null || roleIds.length == 0) return RespBean.error("请至少选择一个角色！");

        Admin adminNickName = adminService.getOne(new QueryWrapper<Admin>().eq("admin_nickName", admin.getAdminNickname()));
        Integer adminId = admin.getAdminId();
        //保证用户名的唯一性
        if (adminNickName != null && !adminNickName.getAdminId().equals(adminId)) {
            return RespBean.error("用户名重复！");
        }

        admin.setUpdateTime(new Date());
        if (adminService.updateById(admin)) {
            //先删除原先所具有的角色，然后再为其赋予新的角色
            if (adminRoleService.removeById(adminId)) {
                AdminRole adminRole = new AdminRole().setAdminId(adminId);
                for (Integer roleId : roleIds) {
                    adminRole.setRoleId(roleId);
                    adminRoleService.save(adminRole);
                }
            }
        }
        return RespBean.error("更新管理员信息失败！");
    }

    @ApiOperation("删除管理员")
    @DeleteMapping("/deleteAdmin/{id}")
    public RespBean deleteAdmin(@PathVariable Integer id) {
        if (adminService.removeById(id)) {
            adminRoleService.removeById(id);
            return RespBean.success("删除管理员成功！");
        }
        return RespBean.error("删除管理员失败！请稍后再试");
    }

    @ApiOperation("登录")
    @PostMapping("login")
    public Map<String, Object> UserLogin(HttpServletRequest request, String username, String password) {
        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Admin admin = adminService.userlogin(username, password);
        if (admin != null) {
            result.put("result", "success");
/*            JSONObject json = new JSONObject(result);
            System.out.println(json);*/
            request.getSession().setAttribute(Constant.USER_SESSION, admin);
            LoginRecord lr = new LoginRecord();
            lr.setLoginname(username);
            lr.setLogindate(sbf.format(d));
            adminService.addloginrecord(lr);

            /*this.doPostJson("http://pc.hive-intel.com/api/user/signIn", "{ \"passport\":\"dhnjyf1\", \"password\":\"123123\"}");*/
        } else {
            result.put("result", "error");
        }
        return result;
    }

    @ApiOperation("退出登录")
    @GetMapping("logout")
    public void logout(HttpServletRequest request) {
        request.getSession().removeAttribute(Constant.USER_SESSION);
    }

    @GetMapping("SessionMap")
    public Map<String, Object> SessionMap(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Admin a = ((Admin) session.getAttribute(Constant.USER_SESSION));
        result.put("loginname", a.getAdminNickname());
        return result;
    }

    //蜂巢登录接口
    public String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

}

